/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.sales.generics.client.utils;

import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.ui.TextBox;

/**
 *
 * @author v
 */
public class NumbersUtils {

    public static String getFormatted(double value, int decimalCount) {
        StringBuilder numberPattern = new StringBuilder(
                (decimalCount <= 0) ? "" : ".");
        for (int i = 0; i < decimalCount; i++) {
            numberPattern.append('0');
        }
        return NumberFormat.getFormat(numberPattern.toString()).format(value);
    }

    public static Number toNumber(String value) {
        return Double.parseDouble(value.replaceAll("[^0-9.,]", ""));
    }

    public static class NumbersOnly implements KeyPressHandler {

        @Override
        public void onKeyPress(KeyPressEvent event) {
            int keyCode = event.getNativeEvent().getKeyCode();
            if ((!Character.isDigit(event.getCharCode()))
                    && (keyCode != KeyCodes.KEY_TAB)
                    && (keyCode != KeyCodes.KEY_BACKSPACE)
                    && (keyCode != KeyCodes.KEY_DELETE)
                    && (keyCode != KeyCodes.KEY_HOME)
                    && (keyCode != KeyCodes.KEY_END)
                    && (keyCode != KeyCodes.KEY_LEFT)
                    && (keyCode != KeyCodes.KEY_UP)
                    && (keyCode != KeyCodes.KEY_RIGHT)
                    && (keyCode != KeyCodes.KEY_DOWN)) {
                ((TextBox) event.getSource()).cancelKey();
            }
        }
    }
}
